import { _decorator, bits, Collider2D, Color, Component, Contact2DType, Node, randomRangeInt, toDegree, tween, Tween, Vec2, Vec3 } from 'cc';
import { Battle } from './Battle';
import { BattleContext } from './BattleContext';
import { Constant } from './Constant';
import { Util } from './Util';
import { Weapon } from './Weapon';
import { Sword } from './Sword';
import { Globals } from './Globals';
import { FireExplode } from './FireExplode';
import { Bullet } from './Bullet';
import { Camera } from './Camera';
import { BuffHolder } from './Buff';
import { Ebullet } from './Ebullet';
const { ccclass, property } = _decorator;

@ccclass('Monster')
export class Monster extends Component {

    speed:number = 2;   // 移动速度
    moveDirection:number = 0; // 弧度
    isMoving:boolean = false; // 是否移动中

    hp:number = 100; // 血量
    ap:number = 10; // 攻击力
    dp:number = 5; // 防御力

    static readonly Event = {
        DEAD: 0,
        
    }


    private _buffHolder = new BuffHolder();
    private _cb: Function;
    private _target: any;


    protected onEnable(): void {
        // 碰撞事件的接口
        const collider = this.node.getComponent(Collider2D);
        if(collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }

        this.hp = 100;
        this._buffHolder.onCallback((uid:number,value:number,color:string)=> {
            this.hurt(value,color);
        })
    }

    protected onDisable(): void {
        // 碰撞事件的接口
        const collider = this.node.getComponent(Collider2D);
        if(collider) {
            collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.off(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
    }


    start() {
        this.isMoving = true;
        this.schedule(()=> {
            if(!BattleContext.ndPlayer || !BattleContext.ndPlayer.isValid) return;
            const deltaX = BattleContext.ndPlayer.worldPosition.x - this.node.worldPosition.x;
            const deltaY = BattleContext.ndPlayer.worldPosition.y - this.node.worldPosition.y;
            this.moveDirection = Math.atan2(deltaY, deltaX); // 计算与玩家的角度
            // this.moveDirection = Math.atan2()
        }, 0.1)
    }

    update(deltaTime: number) {
        this._buffHolder.update(deltaTime)

        if(this.isMoving) {
            const x = this.node.position.x + Math.cos(this.moveDirection) * this.speed;
            const y = this.node.position.y + Math.sin(this.moveDirection) * this.speed;
            this.node.setPosition(x,y,0);
        }
    }




    hurt(val:number, color: string = '#FFFFFF') {
        this.hp -= val;
        Util.showText(`${val}`, color, this.node.worldPosition, BattleContext.ndTextParent);
        if(this.hp <= 0) {
            this._cb && this._cb.apply(this._target, [Monster.Event.DEAD])
            this.node.destroy();
        }
    }

    onMonsterEvent(cb: Function, target?: any) {
        this._cb = cb;
        this._target = target;
    }

    // 受伤回退
    private _hitBack() {
        const tag = 1;
        Tween.stopAllByTag(tag,this.node);
        
        const inverseRadian = toDegree(toDegree(this.moveDirection) -180);

        const dest = Util.getPosition(this.node.worldPosition, inverseRadian, 50);

        tween(this.node)
        .tag(tag)
        .to(0.2, {worldPosition:dest},{easing: 'expoOut'})
        .start();
    }

    onBeginContact(self: Collider2D, other: Collider2D){
        if(other.group === Constant.ColliderGroup.PLAYER_WEAPON) {
            switch (other.tag) {
                case Constant.WeaponTag.DAGGER:
                    this.hurt(other.node.getComponent(Weapon).attack);
                    break;
                case Constant.WeaponTag.SWORD:
                    this.hurt(other.node.getComponent(Sword).attack);
                    break;
                case Constant.WeaponTag.FIREBALL:
                    // 火球术穿透伤害
                    // Util.showText(
                    //     `${other.node.getComponent(Weapon).attack}`, 
                    //     this.node.worldPosition,
                    //         BattleContext.ndTextParent);
                    // this.hurt(other.node.getComponent(Weapon).attack);
                    // console.log('这里会碰撞多次吗')
                    // TODO 火球爆炸有bug
                    const ndExplode = Globals.getNode(Constant.PrefabUrl.FIRE_EXPLODE, BattleContext.ndWeapon);
                    ndExplode.worldPosition = other.node.worldPosition;
                    ndExplode.getComponent(FireExplode).playAnimation();
                    // Globals.putNode(other.node); // 销毁火球
                    break;
                case Constant.WeaponTag.FIRE_EXPLODE:
                    this.hurt(other.node.getComponent(FireExplode).attack);
                    // 获得buff
                    this._buffHolder.Add(0, '#e9302d', 20, 5, 1)
                    break;
                case Constant.WeaponTag.Bullet:
                    this.hurt(other.node.getComponent(Bullet).attack);
                    this._hitBack();
                    break;
            
                default:
                    break;
            }
        } else if(other.group === Constant.ColliderGroup.PLAYER) { 
            const pos = Util.getPosition(other.node.position, this.moveDirection, 100)
            tween(other.node)
            .to(0.3, {position: pos}, {easing: 'expoOut'})
            .start();
        }
    }

    onEndContact(self: Collider2D, other: Collider2D){

    }

    // 重启技能
    startAction() {
        this.stopAction();

        const pos = new Vec3();
        const action = tween(this.node)
            .delay(randomRangeInt(3, 6))
            .call(()=> {
                Util.getPosition(this.node.position, this.moveDirection, 200, pos);
            })
            .to(0.5, {position: pos}, {easing: 'backIn'})
            .delay(randomRangeInt(1, 3))
            .call(()=> {
                for(let i=0;i<3;i++) {
                    this.scheduleOnce(()=> {
                        this.shootBullet();
                    }, i*1)
                }
            })

        tween(this.node).repeatForever(action).start();
    }

    stopAction() {
        Tween.stopAllByTarget(this.node);
    }

    shootBullet() {
        const ndBullet = Globals.getNode(Constant.PrefabUrl.EBULLET, BattleContext.ndWeapon);
        ndBullet.worldPosition = this.node.worldPosition;
        const wp = ndBullet.getComponent(Ebullet);
        wp.moveDirection = Util.getRadian(this.node.worldPosition, BattleContext.ndPlayer.worldPosition); // 武器的角度
        wp.attack = 10 + this.ap; // 武器的攻击力
        wp.speed = 10;
        wp.isMoving = true;
    }
}


